//
//  MXFooderPlanController.m
//  HNBaseProject
//
//  Created by xujie on 2024/6/4.
//

#import "MXFooderPlanController.h"
#import "MxPublicNav.h"
#import "MXFoodPlanDateCell.h"
#import "MXFoodPlanListCell.h"
#import "MXFooderPlanView.h"
#import "MXFooderRecordController.h"
#import "MXAddPlanController.h"
#import "MXFooderPlanListModel.h"
@interface MXFooderPlanController () <MxNavigationViewDelegate,UICollectionViewDelegate,UICollectionViewDataSource,UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, strong) MxPublicNav *nav;
@property (nonatomic,strong) UICollectionView *listCV;
@property (nonatomic,assign) NSInteger selectIndx;
@property (nonatomic,strong) NSArray *dateArray;
@property (nonatomic, strong) UITableView *listTab;
@property (nonatomic,strong) NSMutableArray *listArray;
@property (nonatomic,assign) NSInteger page;
@property (nonatomic,copy) NSString *dateStr;
@end

@implementation MXFooderPlanController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor colorWithHexString:@"#f4f4f4"];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadList) name:@"addfoodplansuccess" object:nil];
    self.selectIndx = 0;
    self.dateArray = @[@"日",@"一",@"二",@"三",@"四",@"五",@"六"];
    self.listArray = [[NSMutableArray alloc] init];
    self.page = 1;
    self.dateStr = @"7";
    [self createUI];
    [self getPlanListWithDay:@"7"];
}

//计划日期(1-7,单选)
- (void)getPlanListWithDay:(NSString *)day {
    NSDictionary *param = @{@"deviceId" : self.model.ID,
                            @"planDate" : day
                           };
    NSString *urlStr = [NSString stringWithFormat:@"%@?pageNum=%@&pageSize=%@",@"api/app/appFeedingPlan/listByDate",[NSString stringWithFormat:@"%ld",self.page],@"20"];
    MJWeakSelf
    [self.view makeToastActivity];
    [[DCHttpClient shareClient] requestWithPath:urlStr params:param httpMethod:DCHttpRequestPost sucess:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        NSDictionary * dict = [responseObject mj_JSONObject];
        [weakSelf.view hideToastActivity];
        if (dict[DC_ResultCode_Key] && [dict[DC_ResultCode_Key] integerValue] == DC_Result_Success) {
            if (weakSelf.page == 1) {
                [weakSelf.listArray removeAllObjects];
            }
            NSArray *dataArray =  [NSArray modelArrayWithClass:[MXFooderPlanListModel class] json:dict[@"data"][@"list"]];
            [weakSelf.listArray addObjectsFromArray:dataArray];
            [weakSelf.listTab reloadData];
        } else {

            [weakSelf.view xjmakeToast:dict[DC_ResultMsg_Key]];
        }
    } failture:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
        [weakSelf.view hideToastActivity];
    }];
}

- (void)reloadList {
    self.page = 1;
    [self getPlanListWithDay:self.dateStr];
}

- (void)createUI {
    self.nav = [[MxPublicNav alloc] initWithFrame:CGRectMake(0, 0, kScreenW, kNavBarHeight)];
    self.nav.titleLab.text = SAFEPARAMETER(self.model.deviceLocalName);
    self.nav.delegate = self;
    self.nav.backgroundColor = [UIColor clearColor];
    [self.view addSubview:self.nav];
    
    UILabel *titleLab = [[UILabel alloc] init];
    titleLab.text = @"喂食计划";
    titleLab.textColor = [UIColor colorWithHexString:@"#000000"];
    titleLab.font = PFRFontMedium(14);
    [self.view addSubview:titleLab];
    [titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(28);
        make.top.offset(kNavBarHeight+50);
    }];
    
    [self.view addSubview:self.listCV];
    [self.listCV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(25);
        make.right.offset(-25);
        make.top.mas_equalTo(titleLab.mas_bottom).offset(13);
        make.height.mas_equalTo(58);
    }];
    
    [self.view addSubview:self.listTab];
    [self.listTab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(21);
        make.right.offset(-21);
        make.height.mas_equalTo(85.0*3);
        make.top.mas_equalTo(self.listCV.mas_bottom).offset(39);
    }];
    
    MXFooderPlanView *recordV = [[MXFooderPlanView alloc] init];
    [self.view addSubview:recordV];
    [recordV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(21);
        make.right.offset(-21);
        make.height.mas_equalTo(56);
        make.top.mas_equalTo(self.listTab.mas_bottom).offset(39);
    }];
    MJWeakSelf
    [recordV addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithActionBlock:^(id  _Nonnull sender) {
        [weakSelf gotoRecord];
    }]];
    
    MXFooderPlanView *addV = [[MXFooderPlanView alloc] init];
    addV.titleLab.text = @"新增喂食";
    addV.icon.image = [UIImage imageNamed:@"food_add"];
    [self.view addSubview:addV];
    [addV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(21);
        make.right.offset(-21);
        make.height.mas_equalTo(56);
        make.top.mas_equalTo(recordV.mas_bottom).offset(14);
    }];

    [addV addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithActionBlock:^(id  _Nonnull sender) {
        [weakSelf addFood];
    }]];
}

- (UICollectionView *)listCV {
   if (!_listCV) {
       UICollectionViewFlowLayout * layout = [[UICollectionViewFlowLayout alloc]init];
       layout.itemSize = CGSizeMake((kScreenW - 50-42) / 7.0, 58);
       layout.minimumLineSpacing = 7;
       layout.minimumInteritemSpacing = 7;
       layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
       _listCV = [[UICollectionView alloc]initWithFrame:CGRectZero collectionViewLayout:layout];
       _listCV.backgroundColor = [UIColor clearColor];
       _listCV.delegate = self;
       _listCV.dataSource = self;
       _listCV.showsVerticalScrollIndicator = NO;
       _listCV.showsHorizontalScrollIndicator = NO;
       [_listCV registerClass:[MXFoodPlanDateCell class] forCellWithReuseIdentifier:@"MXFoodPlanDateCell"];
       
       }
    return _listCV;
}

#pragma mark - ________ UITableView ________

- (UITableView *)listTab {
    
    if (nil == _listTab) {
        _listTab = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _listTab.backgroundColor = [UIColor whiteColor];
        _listTab.layer.cornerRadius = 8;
        _listTab.layer.masksToBounds = YES;
        _listTab.separatorStyle = UITableViewCellSeparatorStyleNone;
        _listTab.delegate = self;
        _listTab.dataSource = self;
        _listTab.rowHeight = 85.0;
        _listTab.showsVerticalScrollIndicator = NO;
        _listTab.showsHorizontalScrollIndicator= NO;
        [_listTab registerClass:[MXFoodPlanListCell class] forCellReuseIdentifier:NSStringFromClass([MXFoodPlanListCell class])];
        if (@available(iOS 11.0, *)) {
            _listTab.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
        if (@available(iOS 15.0, *)) {
            _listTab.sectionHeaderTopPadding = 0;
        }
    }
    return _listTab;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    MJWeakSelf
    MXFooderPlanListModel *model = self.listArray[indexPath.row];
    MXFoodPlanListCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([MXFoodPlanListCell class])];
    [cell reloadCellWithModel:model];
    cell.valueBlock = ^(BOOL isOn) {
        [weakSelf changeListStateWithModel:model];
    };
    return cell;
    
}


-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{

    return YES;
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
    return UITableViewCellEditingStyleDelete;
}

- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath{
    return @"删除";
}

- (NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath{
    MJWeakSelf;
    UITableViewRowAction *deleteAction= [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"删除" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
        
        MXFooderPlanListModel *model = weakSelf.listArray[indexPath.row];
        [weakSelf deletePlanWithModel:model];
    }];
    deleteAction.backgroundColor=[UIColor colorWithHexString:@"#FE3E3D"];
    return @[deleteAction];
}

- (void)deletePlanWithModel:(MXFooderPlanListModel *)model {

    MJWeakSelf
    NSString *urlStr = [NSString stringWithFormat:@"%@?id=%@",@"api/app/appFeedingPlan/delete",model.ID];
    [self.view makeToastActivity];
    [[DCHttpClient shareClient] requestWithPath:urlStr params:@{} httpMethod:DCHttpRequestPost sucess:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        NSDictionary * dict = [responseObject mj_JSONObject];
        [weakSelf.view hideToastActivity];
        if (dict[DC_ResultCode_Key] && [dict[DC_ResultCode_Key] integerValue] == DC_Result_Success) {
            [weakSelf.view xjmakeToast:@"删除成功"];
            weakSelf.page = 1;
            [weakSelf getPlanListWithDay:weakSelf.dateStr];
        } else {

            [weakSelf.view xjmakeToast:dict[DC_ResultMsg_Key]];
        }
    } failture:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
        [weakSelf.view hideToastActivity];
    }];
}

- (void)changeListStateWithModel:(MXFooderPlanListModel *)model {
    NSInteger state = model.status == 1 ? 0 :1;
    NSString *urlStr = [NSString stringWithFormat:@"%@?id=%@&status=%ld",@"api/app/appFeedingPlan/updateStatus",model.ID,state];
    MJWeakSelf
    [self.view makeToastActivity];
    [[DCHttpClient shareClient] requestWithPath:urlStr params:@{} httpMethod:DCHttpRequestPost sucess:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        NSDictionary * dict = [responseObject mj_JSONObject];
        [weakSelf.view hideToastActivity];
        if (dict[DC_ResultCode_Key] && [dict[DC_ResultCode_Key] integerValue] == DC_Result_Success) {
            [weakSelf.view xjmakeToast:@"修改成功"];
            model.status = state;
            [weakSelf.listTab reloadData];
        } else {

            [weakSelf.view xjmakeToast:dict[DC_ResultMsg_Key]];
        }
    } failture:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
        [weakSelf.view hideToastActivity];
    }];

}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.listArray.count;
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return 7;
}

-(__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{

    MXFoodPlanDateCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"MXFoodPlanDateCell" forIndexPath:indexPath];
    [cell reloadCellWithSelect:(self.selectIndx == indexPath.item) title:self.dateArray[indexPath.item]];
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.item == self.selectIndx) {
        return;
    }
    self.page = 1;
    self.selectIndx = indexPath.item;
    [self.listCV reloadData];
    if (indexPath.item == 0) {
        self.dateStr = @"7";
        [self getPlanListWithDay:@"7"];
    } else {
        self.dateStr = [NSString stringWithFormat:@"%ld",indexPath.item];
        [self getPlanListWithDay:[NSString stringWithFormat:@"%ld",indexPath.item]];
    }
    
}

-(void)leftTap {
    [self.navigationController popViewControllerAnimated:YES];
}

//喂食记录
- (void)gotoRecord {
    MXFooderRecordController *recordVc = [[MXFooderRecordController alloc] init];
    recordVc.model = self.model;
    [self.navigationController pushViewController:recordVc animated:YES];
}

//新增喂食
- (void)addFood {
    MXAddPlanController *planVc = [[MXAddPlanController alloc] init];
    planVc.model = self.model;
    [self presentViewController:planVc animated:YES completion:nil];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self dc_navBarHidden:YES];
}


@end
